package com.authine.cloudpivot.ext.service.ipml;

import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.facade.UserFacade;
import com.authine.cloudpivot.engine.api.model.dto.SimpleMsgDTO;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.enums.type.IMMessageChannelType;
import com.authine.cloudpivot.engine.enums.type.IMMessageType;
import com.authine.cloudpivot.engine.service.impl.component.RuntimeMessageComponent;
import com.authine.cloudpivot.engine.service.message.IMessageService;
import com.authine.cloudpivot.foundation.orm.api.dml.JPANativeQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SyncPetitionresidentImpl {

    private static final String SHEAM_CODE = "petitionresident";

    @Autowired
    JPANativeQuery jpaNativeQuery;

    @Autowired
    private BizObjectFacade bizObjectFacade;

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private UserFacade userFacade;


    public void notice(){

        LocalDate currentDate = LocalDate.now();
        int monthValue = currentDate.getMonthValue();
        monthValue = (monthValue == 1) ? 12 : monthValue - 1;
        String title="超时提醒";
        String sql = "SELECT * FROM `iknn4_petitionresident`";
        List<Map<String,Object>> list = jpaNativeQuery.getList(sql, null, null);
        if (CollectionUtils.isNotEmpty(list)){
            for (Map<String,Object> map : list){
                String id =(String) map.get("id");
                String xfry = (String) map.get("relevanceResident");
                String queryxfryName = String.format("SELECT * FROM `iknn4_resident` where id = '%s'",xfry);
                List<Map<String,Object>> xfryList = jpaNativeQuery.getList(queryxfryName, null, null);
                String xfName = (String) xfryList.get(0).get("residentName");
                String queryww = String.format("select * from iknn4_maintainstabilitys where parentId = '%s'",id);
                List<Map<String,Object>> wwList = jpaNativeQuery.getList(queryww, null, null);
                if (CollectionUtils.isNotEmpty(wwList)){
                    for (Map<String,Object> wwMap : wwList){
                        String ryid = (String) wwMap.get("maintainstability");
                        String zfrz = String.format("select * from iknn4_workLogs where recorder = '%s' and   YEAR(interviewTime) = YEAR(CURDATE())  AND MONTH(interviewTime) = '%s';",ryid,monthValue);
                        List list1 = jpaNativeQuery.getList(zfrz, null, null);
                        if (CollectionUtils.isEmpty(list1) || list1.size()<2){
                            IMessageService messageService = RuntimeMessageComponent.getMessageService(IMMessageChannelType.DINGTALK.name());
                            UserModel user = userFacade.get(ryid);
                            String cont="信访人员【%s】走访工作日志未填写，请及时处理！";
                            cont = String.format(cont,xfName);
                            senDingTalkMessage(messageService,user,title,cont);
                        }
                    }
                }
            }
        }
    }

    private void senDingTalkMessage(IMessageService messageService, UserModel user , String title, String content){

        if (org.apache.commons.lang3.StringUtils.isEmpty(user.getUserId())){
            log.warn("用户钉钉ID为空，不推送钉钉消息！");
            return;
        }

        SimpleMsgDTO dto = new SimpleMsgDTO();
        try {

            //钉钉userId
            dto.setReceivers(user.getUserId());
            dto.setContent(content);
            dto.setTitle(title);
            dto.setMessageType(IMMessageType.BUSINESS_REMIND);
            dto.setCorpId(user.getCorpId());
            messageService.sendSimpleTextMsg(dto);
        } catch (Exception e) {
            log.info("用户：{}-账号：{}，送消息内容：{}",user.getName(),user.getUsername(), JSONObject.toJSONString(dto));
            log.error("钉钉消息发送失败",e);
        }
    }
}
